package com.mmg.spzx.user.service.impl;

import com.mmg.spzx.common.exception.MmgException;
import com.mmg.spzx.model.vo.common.ResultCodeEnum;
import com.mmg.spzx.user.service.SmsService;
import com.mmg.spzx.user.utils.EmailUtil;
import com.mmg.spzx.utils.HttpUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void sendCode(String number) {
        try {
            String code = redisTemplate.opsForValue().get("sms:code:" + number);
            if (StringUtils.hasText(code)) {
                throw new Exception("验证码还未失效，请勿重复发送！");
            }
            String validateCode = RandomStringUtils.randomNumeric(6);      // 生成验证码
            redisTemplate.opsForValue().set("sms:code:" + number, validateCode, 5, TimeUnit.MINUTES);
            System.out.println("验证码：" + validateCode);
            if (number.contains("@")) {
                // 发送邮件
                sendEmail(number, validateCode);
            } else {
                // 发送短信
                //sendSms(number, validateCode);
                throw new Exception("短信服务暂未开启哦！");
            }
        } catch (Exception e) {
            if (e.getMessage().contains("验证码还未失效，请勿重复发送！")) {
                throw new MmgException(500, e.getMessage());
            }
            //其他情况发送失败，删除redis中的验证码
            redisTemplate.delete("sms:code:" + number);
            throw new MmgException(500, e.getMessage());
        }
    }

    private void sendEmail(String number, String validateCode) {
        try {
            EmailUtil.sendSimpleMail(number, "【尚品甄选】注册验证码", "您的验证码为：" + validateCode + "，5分钟内有效。");
        } catch (Exception e) {
            throw new MmgException(500, e.getMessage());
        }
    }

    /**
     * 发送短信方法
     */
    public void sendSms(String phone, String validateCode) {
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = "938a8491cea74e43a48edf0a67070051";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("content", "code:" + validateCode);
        bodys.put("template_id", "CST_ptdie100");
        bodys.put("phone_number", phone);

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new MmgException(ResultCodeEnum.SYSTEM_ERROR);
        }
    }
}
